package com.qubuyer.business.order

import androidx.lifecycle.MutableLiveData
import com.qubuyer.repository.entitys.OrderEntity
import com.qubuyer.business.good.viewmodel.SOModel
import com.qubuyer.core.anno.AutoInject
import com.qubuyer.core.ext.toast
import com.qubuyer.core.framework.BaseViewModel
import com.qubuyer.core.http.RetrofitCall
import com.qubuyer.repository.entitys.GoodSOResultEntity
import com.qubuyer.repository.entitys.PayResultEntity
import com.qubuyer.repository.entitys.WechatPayParamEntity
import com.qubuyer.utils.WechatUtils

class PayOrderViewModel : BaseViewModel() {
    var mOrderEntity: OrderEntity? = null
    var mSOEntity: GoodSOResultEntity? = null
    var orderId: String? = null
    var payType: Int = 1
    var wxParams = MutableLiveData<WechatPayParamEntity>()
    var aliParams = MutableLiveData<String>()
    var payResult = MutableLiveData<PayResultEntity>()

    @AutoInject
    val soModel = SOModel()

    fun getOrderPayResult() {
        RetrofitCall<PayResultEntity?>(lifecycleOwner, this) {
            api { soModel.getOrderStatus(orderId ?: "") }
            success { payResult.value = it }
        }
    }

    fun pay() {
        when (payType) {
            1 -> {
                if (WechatUtils.isWeChatAppInstalled()) {
                    getWeChatPayParam()
                } else {
                    lifecycleOwner?.toast("请安装最新版微信");
                }
            }
            2 -> getAlipayParam()
        }
    }

    private fun getAlipayParam() {
        RetrofitCall<String?>(lifecycleOwner, this) {
            api { soModel.getAliPayParams(orderId ?: "") }
            success { aliParams.value = it }
        }
    }

    private fun getWeChatPayParam() {
        RetrofitCall<WechatPayParamEntity?>(lifecycleOwner, this) {
            api { soModel.getWxPayParams(orderId ?: "") }
            success { wxParams.value = it }
        }
    }
}